import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, Input, Space, Table, Tag } from 'antd';
import dayjs from 'dayjs';

import { store } from '@/store';

import { HiddenDangerObj } from '@/enum/safety';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  safeInspectionPlanAdd,
  safeInspectionPlanGet,
  safeInspectionPlanUpdate
} from '@/services/bizApi/anquanpaichajihuajiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';
import Ledger, { LedgerRef } from './ledger';

type DataSourceType = {
  key: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: number;
  update_at?: number;
  children?: DataSourceType[];
};

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  const ledger = useRef<LedgerRef>(null);
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [dataSource, setDataSource] = useState<BIZAPI.SafeHazardInfoEntity[]>([]);
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );

  const safeInspectionPlan = useRequest(
    async (id: string) => {
      const res = await safeInspectionPlanGet({ id });
      const data = res?.data;
      // 回填数据
      form.setFieldsValue({
        ...res?.data,
        planDate: dayjs(res?.data?.planDate)
      });
      setDataSource((data?.hazardList as unknown as BIZAPI.EquInfoEntity[]) || []);
    },
    {
      manual: true
    }
  );

  const submit = useRequest(
    async ({ _type, ...values }) => {
      if (!dataSource?.length) {
        store.app?.message.info('请添加详情');
        return;
      }
      const query = {
        ...values,
        planDate: values?.planDate ? dayjs(values?.planDate).format('YYYY-MM-DD') : undefined,
        dutyUserName: userInfo?.data?.filter((item) => item.id === values?.dutyUserId)?.[0]
          ?.fullName,
        hazardIds: dataSource?.map((item) => item?.id)?.join(',')
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? safeInspectionPlanUpdate(query)
        : safeInspectionPlanAdd(query));

      args?.onSuccess?.();
      setOpen(false);
      setDataSource([]);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            safeInspectionPlan.run(arg?.rowData?.id as unknown as string);
            // 回填数据
            // form.setFieldsValue({
            //   ...arg.rowData
            // });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
    setDataSource([]);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增排查计划',
          edit: '编辑排查计划',
          detail: '排查计划详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="排查日期"
          name="planDate"
          rules={[
            {
              required: true,
              message: '请选择排查日期'
            }
          ]}
        >
          <DatePicker placeholder="请选择排查日期" style={{ width: '100%' }} />
        </Form.Item>
        <ProFormSelect
          name="dutyUserId"
          label="负责人"
          placeholder="请选择负责人"
          showSearch={true}
          rules={[{ required: true, message: '请选择负责人' }]}
          request={async () => {
            const res = await orgUserInfoVoPage({ page: 1, size: 1000 });
            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <Form.Item
          label="备注"
          name="remark"
          rules={[
            {
              required: false,
              message: '请输入备注'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入备注" />
        </Form.Item>
      </Form>
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          width: '100%',
          padding: '20px 24px 10px'
        }}
      >
        <div style={{ fontSize: '16px' }}>详情</div>
        <Button
          type="primary"
          disabled={args?.type === 'detail'}
          onClick={() => {
            ledger.current?.open({
              onSuccess: (rows) => {
                const arr = rows?.filter(
                  (item) => !dataSource?.some((itm) => itm?.id === item?.id)
                );
                setDataSource([...dataSource, ...arr]);
              }
            });
          }}
        >
          添加数据
        </Button>
      </div>
      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: '隐患名称',
            dataIndex: 'name'
          },
          {
            title: '隐患类型',
            dataIndex: 'type',
            render: (v) => {
              const obj = HiddenDangerObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '隐患内容',
            dataIndex: 'content'
          },
          {
            title: '整改截止时间',
            dataIndex: 'dueTime'
          },
          {
            title: '操作',
            fixed: 'right',
            width: 150,
            hidden: args?.type === 'detail',
            render: (text, record) => [
              <a
                key="delete"
                onClick={() => {
                  if (args?.type === 'detail') return;
                  setDataSource(dataSource.filter((item) => item.id !== record.id));
                }}
              >
                删除
              </a>
            ]
          }
        ]}
        dataSource={dataSource}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        // {...table.tableProps}
        pagination={
          {
            // ...table.tableProps.pagination,
            // showTotal: (total) => `共 ${total} 条`,
            // showQuickJumper: true,
            // showSizeChanger: true,
            // pageSizeOptions: ['10', '20', '50', '100']
          }
        }
      />
      {/* end表格 */}
      <Ledger ref={ledger} />
    </Drawer>
  );
};

export default forwardRef(Edit);
